package com.hnichr.ump.talent.library.service.impl;

import com.hnichr.ump.common.talent.library.entity.Area;
import com.hnichr.ump.common.talent.library.entity.EducationInfo;
import com.hnichr.ump.common.talent.library.entity.PersonalInfo;
import com.hnichr.ump.common.talent.library.entity.Resume;
import com.hnichr.ump.common.talent.library.service.AreaService;
import com.hnichr.ump.common.talent.library.service.ResumeService;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import com.mxpioframework.jpa.query.Order;
import com.mxpioframework.system.service.impl.BaseServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class ResumeServiceImpl extends BaseServiceImpl<Resume> implements ResumeService {

    @Autowired
    private AreaService areaService;

    @Override
    @Transactional(readOnly = true)
    public List<Resume> listAll() {
        return JpaUtil.linq(Resume.class).list();
    }

    @Override
    @Transactional(readOnly = true)
    public List<Resume> getByUserId(String userId){
        return JpaUtil.linq(Resume.class).equal("userId",userId).list();
    }

    @Override
    @Transactional(readOnly = true)
    public Page<Resume> listPage(Pageable page, Criteria c){
        if(c!=null){
            c.addCriterion("type", Operator.EQ,0);
            c.addCriterion("delFlag", Operator.EQ,false);
            c.addOrder(new Order("orginalCreateTime",true));
        }
        Page<Resume> resumePage = this.listPage(Resume.class,page,c);
        if(CollectionUtils.isEmpty(resumePage.getContent())){
            return resumePage;
        }

        Set<String> userIds = JpaUtil.collect(resumePage.getContent(),"userId");
        List<PersonalInfo> personalInfos = JpaUtil.linq(PersonalInfo.class).in("userId",userIds).equal("delFlag",false).like("roleType","0%").list();
        Map<String,PersonalInfo> personalInfoMap = JpaUtil.index(personalInfos,"userId");
        for(Resume resume:resumePage.getContent()){
            if(personalInfoMap.containsKey(resume.getUserId())){
                resume.setPersonalInfo(personalInfoMap.get(resume.getUserId()));
            }
            else{
                //防止前端取值报错
                resume.setPersonalInfo(new PersonalInfo());
            }
            translateDictField(resume);
        }
        return resumePage;
    }

    @Override
    @Transactional(readOnly = true)
    public Resume getById(String id){
        Resume resume = super.getById(Resume.class,id);
        if(resume==null){
            throw new NullPointerException();
        }
        List<PersonalInfo> personInfos = JpaUtil.linq(PersonalInfo.class).equal("userId",resume.getUserId()).equal("delFlag",false).like("roleType","0").list();
        if(CollectionUtils.isNotEmpty(personInfos)){
            resume.setPersonalInfo(personInfos.get(0));
        }
        /*else{
            resume.setPersonalInfo(new PersonalInfo());
        }*/
        return resume;
    }

    @Override
    @Transactional(readOnly = true)
    public List<Resume> getBySyncDate(String syncDate) {
        return JpaUtil.linq(Resume.class).equal("syncDate",syncDate).list();
    }

    private void translateDictField(Resume resume){
        resume.setResumeTypeStr((resume.getResumeType()==1)?"社招":"校招");
        resume.setLanTypeStr((resume.getLanType()==0)?"中文":"英文");

        List<EducationInfo> eduList = JpaUtil.linq(EducationInfo.class).equal("resumeId",resume.getId()).equal("delFlag",false).desc("startTime").list();
        if(CollectionUtils.isNotEmpty(eduList)){
            EducationInfo highestEdu = eduList.stream().max(Comparator.comparingInt(EducationInfo::getEduLevel)).get();
            resume.setHighestDegree(getEduLevelStr(highestEdu.getEduLevel()));
            EducationInfo firstEdu = eduList.stream().filter(e -> e.getEduLevel() > 2 && StringUtils.equals(e.getFullTime(), "1")).max(Comparator.comparing(EducationInfo::getStartTime)).orElse(null);
            if(firstEdu != null){
                resume.setFirstDegree(getEduLevelStr(firstEdu.getEduLevel()));
            }
        }

        if(resume.getPersonalInfo()!=null){
            PersonalInfo personalInfo = resume.getPersonalInfo();
            //性别
            personalInfo.setSexStr(getSexStr(personalInfo.getSex()));

            //户口所在地/现居地
            String hownTown = personalInfo.getHomeTown();
            String liveCity = personalInfo.getLiveCity();
            personalInfo.setHomeTown(getDistrict(hownTown));
            if(StringUtils.equals(hownTown,liveCity)){
                personalInfo.setLiveCity(personalInfo.getHomeTown());
            }
            else{
                personalInfo.setLiveCity(getDistrict(liveCity));
            }

            //身份
            personalInfo.setIdEntityStr(getIdEntityStr(personalInfo.getIdEntity()));

            //婚姻状况
            personalInfo.setMaritalStatusStr(getMaritalStatusStr(personalInfo.getMaritalStatus()));

        }
    }

    private String getEduLevelStr(Integer eduLevel){
        String [] eduLevels = {"初中", "高中", "中专/中技", "大专", "本科", "研究生", "MBA/EMBA", "博士"};
        return eduLevel == null ? "无" : eduLevels[eduLevel];
    }

    private String getSexStr(Integer sex){
        if(sex==null){
            return "";
        }
        if(sex==1){
            return "男";
        }
        else if(sex==2){
            return "女";
        }
        else{
            return "";
        }
    }

    private String getDistrict(String district){
        if(StringUtils.isBlank(district)){
            return "";
        }
        String [] areaIds = district.split(",");
        StringBuffer sbArea = new StringBuffer();
        for(String areaId:areaIds){
            Area area = areaService.getById(Area.class,areaId);
            if(area!=null){
                sbArea.append(area.getName());
            }
        }
        return sbArea.toString();
    }

    private String getIdEntityStr(Integer idEntity){
        if(idEntity==null){
            return "";
        }
        if(idEntity==1){
            return "职场人";
        }
        else if(idEntity==2){
            return "应届生";
        }
        else if(idEntity==3){
            return "在校生";
        }
        else{
            return "";
        }
    }

    private String getMaritalStatusStr(Integer maritalStatus){
        if(maritalStatus==null){
            return "";
        }
        if(maritalStatus==0){
            return "未婚";
        }
        else if(maritalStatus==1){
            return "已婚已育";
        }
        else if(maritalStatus==2){
            return "已婚未育";
        }
        else if(maritalStatus==3){
            return "离异";
        }
        else{
            return "";
        }
    }

}
